<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="排序" prop="bannerSort">
        <el-input v-model="queryParams.bannerSort" placeholder="请输入排序" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="显示" :value="1" />
          <el-option label="不显示" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="indexTextShow = !indexTextShow">首页文字描述</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="id主键" align="center" prop="id" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图说明" align="center" prop="content" />
      <el-table-column label="图片" align="center" prop="url">
        <template v-slot="scope">
          <div class="imgboxlun" v-if="scope.row.url">
            <img class="imgstylelun" :src="scope.row.url" alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="bannerSort" />
      <el-table-column label="状态" align="center" prop="status" >
        <template v-slot="scope">
          <span>{{ isstatus[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="imgDetailhandleUpdate(scope.row)">图片详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="handleclose(scope.row)">{{scope.row.status === 1 ?'关闭展示':'开启展示'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog
      title="描述"
      :visible.sync="indexTextShow"
      width="30%">
      <div>
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入首页文字描述"
          v-model="indexText">
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="indexTextShow = false">取 消</el-button>
        <el-button type="primary" @click="saveText">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="700px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播图说明">
          <el-input v-model="form.content" placeholder="请输入轮播图说明" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="uploadSectionFileimgInfo"
              :on-remove="handleRemoveimgInfo"
              :file-list="filelistimgInfo"
              :limit="1"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="bannerSort">
          <el-input v-model="form.bannerSort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" clearable size="small">
            <el-option label="普通banner" :value="1" />
            <el-option label="抽奖活动" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.status===2" label="抽奖轮盘" prop="tid">
          <el-select v-model="form.tid" placeholder="抽奖轮盘" clearable size="small">
            <el-option v-for="item in tableNameList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable size="small">
            <el-option label="显示" :value="1" />
            <el-option label="不显示" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片详情(添加 / 修改) -->
    <el-dialog title="图片详情(添加 / 修改)" :visible.sync="imgDetailShow" width="700px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="图片" prop="url">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="imgDetailonFile"
              :on-remove="handleRemoveimgInfo"
              :file-list="filelistimgInfo"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imgDetailSubmitForm">确 定</el-button>
        <el-button @click="imgDetailShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createBanner,
  updateBanner,
  deleteBanner,
  getBanner,
  getBannerPage,
  exportBannerExcel,
  getTurnList
} from "@/api/qd/banner";
import Editor from '@/components/Editor';

export default {
  name: "Banner",
  components: {
    Editor
  },
  data() {
    return {
      //轮盘名称list
      tableNameList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序-banner列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        content: null,
        url: null,
        bannerSort: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      actives: process.env.VUE_APP_BASE_API+'/pc/file/upload',
      headers:{Authorization: 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')} ,
      filelistimgInfo:[], // 图片上传数组
      isstatus:{1:'显示',2:'不显示'},
      indexText:'',  // 文字展示值
      indexTextShow:false,
      // 图片详情
      imgDetailShow:false,
    };
  },
  created() {
    this.getList();
    this.getIndexText()
    this.getTurnList()
  },
  methods: {
    getTurnList(){
      getTurnList().then(response => {
        this.tableNameList = response.data;
      });
    },
    imgDetailhandleUpdate(row){ // 图片详情修改
      this.reset();
      const id = row.id;
      getBanner(id).then(response => {
        this.form = response.data;
        this.filelistimgInfo = []
        if(this.form.urlList instanceof Array){
          this.filelistimgInfo = this.form.urlList.map(item=>{return {url:item}})
        }
        this.imgDetailShow = true;
      });
    },
    imgDetailSubmitForm(){  // 修改图片详情弹窗确认按钮
      if(this.filelistimgInfo.length == 0) return this.$message.warning('最少上传一张')
      let arr = this.filelistimgInfo.map(item=>item.url)
      updateBanner({...this.form,urlList:arr}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.imgDetailShow = false;
        this.getList();
      });
    },
    imgDetailonFile(val){ // 详情图片上传
      let file = val.file
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {

            this.filelistimgInfo.push({url:res.data})
            this.$message.success('上传成功')
        })
    },
    uploadSectionFileimgInfo(val){ // 轮播图图片上传
      let file = val.file
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {

            this.filelistimgInfo=[{url:res.data}]
            this.form.url = res.data
            this.$message.success('上传成功')
        })
    },
    handleRemoveimgInfo(file, fileList){ // 移除图片时
      this.filelistimgInfo = fileList
      this.form.url = null
    },
    saveText(){  // 首页文字保存
      this.$axios({url:'/qd/banner/updateInfo?content='+this.indexText,method:'get'}).then(res=>{
        this.$message.success('修改成功')
        this.indexTextShow = false
        this.getIndexText()
      })
    },
    getIndexText(){
      this.$axios({url:'/qd/banner/getInfo',method:'get'}).then(res=>{
        this.indexText = res.data ?? ''
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getBannerPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        content: undefined,
        url: undefined,
        bannerSort: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$set(this.form,'status',1)
      this.filelistimgInfo = []
      this.open = true;
      this.title = "添加小程序-轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getBanner(id).then(response => {
        this.form = response.data;
        this.filelistimgInfo=[{url:this.form.url}]
        this.open = true;
        this.title = "修改小程序-轮播图";
      });
    },
    handleclose(row){ // 关闭展示
      this.$axios({url:'/qd/banner/updateStatus?id='+row.id,method:'get'}).then(res=>{
        this.$message.success('操作成功')
        this.getList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      if(!this.form.url) return this.$message.warning('请上传图片')
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        if(this.form.tid){
          this.form.tname = this.tableNameList.find(i=>i.id == this.form.tid)?.name ?? ''
          
        }
        // 修改的提交
        if (this.form.id != null) {
          updateBanner(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createBanner(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除?').then(function() {
          return deleteBanner(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有小程序-banner数据项?').then(() => {
          this.exportLoading = true;
          return exportBannerExcel(params);
        }).then(response => {
          this.$download.excel(response, '小程序-banner.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/minImgStyle.scss";
.imgstylelun{
  width:150px;
  height: 100px;
}
</style>
